package qq_bot

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"strings"
	"zy_bot_demo/viper"
)

type Req struct {
	PostType    string `json:"post_type" form:"post_type"`
	SelfId      int64  `json:"self_id" form:"self_id"`
	Message     string
	MessageType string `json:"message_type" form:"message_type"`
	UserId      int64  `json:"user_id" form:"user_id"`
	GroupId     int64  `json:"group_id"`
}

func random(min, max int) int {
	return rand.Intn(max-min) + min
}

func IsInArray(arr []int64, target int64) bool {
	for _, val := range arr {
		if val == target {
			return true
		}
	}
	return false
}

func StartQQBot() {
	// 初始化 工作协程
	InitWorker()
	engine := gin.Default()

	engine.POST("/", func(ctx *gin.Context) {
		var req Req
		ctx.ShouldBindJSON(&req)
		if req.PostType == "message" {

			if req.MessageType == "private" {

				if req.UserId == 1532724674 || req.UserId == 2102733735 {
					//message, _ := SendMessage(req.Message)

					task := GroupTask{
						GroupId: req.GroupId,
						UserId:  req.UserId,
						Message: req.Message,
					}
					worker.PutGroupTask(task)
					ctx.JSON(http.StatusOK, gin.H{
						//"reply": "大美女" + strconv.Itoa(random(0, 100000)),
						//"reply": fmt.Sprintf("[CQ:at,qq=%v]", req.UserId) + message.Choice[0].Message.Content,
						"reply": fmt.Sprintf("[CQ:at,qq=%v]", req.UserId) + "请稍等片刻。。。",
					})

				} else {
					//message, _ := SendMessage(req.Message)
					task := GroupTask{
						GroupId: req.GroupId,
						UserId:  req.UserId,
						Message: req.Message,
					}
					worker.PutGroupTask(task)
					ctx.JSON(http.StatusOK, gin.H{
						//"reply": fmt.Sprintf("[CQ:at,qq=%v]", req.UserId) + message.Choice[0].Message.Content,
						"reply": fmt.Sprintf("[CQ:at,qq=%v]", req.UserId) + "请稍等片刻。。。",
					})
				}
				//} else if IsInArray(GroupIds, req.GroupId) {
			} else if IsInArray(viper.Config.Qq.GroupIds, req.GroupId) {
				// 不是艾特自己的不管
				if !strings.HasPrefix(req.Message, fmt.Sprintf("[CQ:at,qq=%v]", 2102733735)) {
					return
				}
				userSentToBotMsg := req.Message[21:]
				//message, _ := SendMessage(userSentToBotMsg)
				task := GroupTask{
					GroupId: req.GroupId,
					UserId:  req.UserId,
					Message: userSentToBotMsg,
				}
				worker.PutGroupTask(task)
				ctx.JSON(http.StatusOK, gin.H{
					//"reply": "鸡你太美。。。" + strconv.Itoa(random(0, 100000)),
					//"reply": fmt.Sprintf("[CQ:at,qq=%v]", req.UserId) + message.Choice[0].Message.Content,
					"reply": fmt.Sprintf("[CQ:at,qq=%v]", req.UserId) + "请稍等片刻。。。",
				})
			}
		}

	})

	engine.Run()
}

func init() {

}
